package it.av.training.rest.service.web.security;

import javax.servlet.http.HttpSession;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * Classe di utilita' per accesso dati in sessione
 * 
 * @author alessandro vincelli
 * 
 */
public class SessionUtils {

    /**
     * 
     * @return
     */
    public static HttpSession session() {
        ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
        return attr.getRequest().getSession(true); // true == allow create
    }

    /**
     * Restituisce l'utente corrente, null altrimenti
     * 
     * @return
     */
    public static Object currentLoggedUser() {
        SecurityContext securityContext = SecurityContextHolder.getContext();
        Authentication authentication = securityContext.getAuthentication();
        if (authentication != null) {
            return authentication.getPrincipal();
        }
        return null;
    }
}
